package com.study.leetcode;

import java.util.Arrays;
import java.util.OptionalInt;

public class Solution_395 {
    public static int longestSubstring(String s, int k) {
        /**
         * 基础思想是
         * 先统计当前字符串的每个字符出现的个数
         * 如果某个字符出现次数低于k则当前字符把字符串切割成两份
         * 分别检查这两份字符串中出现次数大于k的字串
         * 例如 aaaaccbbbbddddd  3
         * 因为cc出现的次数低于三所以只需要检测 aaaa bbbbddddd中出现次数大于k的最大字串即可
         */
        int length = s.length();
        if (length == 0) {
            return 0;
        }
        int[] counters = new int[26];
        for (int i = 0; i < s.length(); i++) {
            counters[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < length; i++) {
            int count = counters[s.charAt(i) - 'a'];
            if (0 < count && count < k) {
                return Math.max(
                        longestSubstring(s.substring(0, i), k),
                        longestSubstring(s.substring(i + 1, length), k)
                );
            }
        }
        return length;
    }

    public static int longestSubstring1(String s, int k) {
        int length = s.length();
        if (length == 0) {
            return 0;
        }
        int[] counters = new int[26];
        for (int i = 0; i < s.length(); i++) {
            counters[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < length; ) {
            int counter = counters[s.charAt(i) - 'a'];
            if (0 < counter && counter < k) {
                s = s.replace(s.charAt(i), ' ');
                i += counter;
            } else {
                i++;
            }
        }
        OptionalInt max = Arrays.stream(s.split(" "))
                .filter(String::isEmpty)
                .filter(item -> item.length() > k)
                .mapToInt(String::length)
                .max();
        if (max.isPresent()) {
            return max.getAsInt();
        }
        return s.length();
    }

    public static void main(String[] args) {
        int i = longestSubstring1("aabb", 3);
        System.out.println("i = " + i);
    }
}
